<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="练习日期" prop="practiceDate">
        <el-date-picker clearable
                        v-model="queryParams.practiceDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择练习日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="刷题数量" prop="questionCount">
        <el-input
          v-model="queryParams.questionCount"
          placeholder="请输入刷题数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学习时间" prop="studyTime">
        <el-input
          v-model="queryParams.studyTime"
          placeholder="请输入学习时间"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['hyg:practice:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['hyg:practice:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['hyg:practice:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['hyg:practice:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-trophy"
          size="mini"
          @click="handleRanking"
          v-hasPermi="['hyg:practice:ranking']"
        >处理今日排名</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="practiceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="记录ID" align="center" prop="id" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="练习日期" align="center" prop="practiceDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.practiceDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="刷题数量" align="center" prop="questionCount" />
      <el-table-column label="学习时间" align="center" prop="studyTime" />
      <el-table-column label="当日排名" align="center" prop="rank" />
      <el-table-column label="奖励积分" align="center" prop="pointsAwarded" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['hyg:practice:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['hyg:practice:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="练习日期" prop="practiceDate">
          <el-date-picker clearable
                          v-model="form.practiceDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择练习日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="刷题数量" prop="questionCount">
          <el-input v-model="form.questionCount" placeholder="请输入刷题数量" />
        </el-form-item>
        <el-form-item label="学习时间" prop="studyTime">
          <el-input v-model="form.studyTime" placeholder="请输入学习时间" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPractice, getPractice, delPractice, addPractice, updatePractice, exportPractice, processRanking } from "@/api/hyg/practice"

export default {
  name: "Practice",
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      practiceList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        practiceDate: null,
        questionCount: null,
        studyTime: null,
      },
      form: {},
      rules: {
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        practiceDate: [
          { required: true, message: "练习日期不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      listPractice(this.queryParams).then(response => {
        this.practiceList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        id: null,
        userId: null,
        practiceDate: null,
        questionCount: null,
        studyTime: null,
        createTime: null,
      }
      this.resetForm("form")
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加一日一练记录"
    },
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getPractice(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改一日一练记录"
      })
    },
    handleRanking() {
      this.$modal.confirm('确定要处理今天的排名并发放积分奖励吗？').then(() => {
        const today = new Date();
        const formattedDate = this.parseTime(today, '{y}-{m}-{d}');

        processRanking(formattedDate).then(response => {
          this.$modal.msgSuccess(response.msg || "排名处理成功");
          // 重新加载当前日期数据
          this.queryParams.practiceDate = formattedDate;
          this.handleQuery();
        }).catch(error => {
          this.$modal.msgError("处理排名失败：" + (error.message || "未知错误"));
          console.error("处理排名错误:", error);
        });
      }).catch(() => {});
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 先检查是否已存在记录
          listPractice({
            userId: this.form.userId,
            practiceDate: this.form.practiceDate
          }).then(response => {
            // 修改检查逻辑，确保只有当记录存在且不是当前编辑的记录时才报错
            const existingRecords = response.rows.filter(item =>
              item.userId == this.form.userId &&
              item.practiceDate == this.form.practiceDate &&
              (!this.form.id || item.id != this.form.id)
            );

            if (existingRecords.length > 0) {
              this.$modal.msgError("该用户当天已有练习记录，请修改现有记录");
            } else {
              if (this.form.id != null) {
                updatePractice(this.form).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                })
              } else {
                addPractice(this.form).then(response => {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                })
              }
            }
          })
        }
      })
    },
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除一日一练记录编号为"' + ids + '"的数据项？').then(function() {
        return delPractice(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    handleExport() {
      this.download('hyg/practice/export', {
        ...this.queryParams
      }, `practice_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
